package controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.spi.http.HttpContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;

import util.DateJsonValueProcessor;
import util.ExcelHelper;
import util.ObjectExcelView;

import com.zxf.pojo.Article;
import com.zxf.pojo.Content;
import com.zxf.pojo.Params;
import com.zxf.service.ArticleService;

@Controller
@RequestMapping("/articles")
public class ArticleController {

	@Autowired
	private ArticleService articleService;

	private static Logger logger = Logger.getLogger(ArticleController.class);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	// 保存文章
	@ResponseBody
	@RequestMapping(value = "/savearticle.do", method = RequestMethod.POST)
	public void savearticle(Article article, String publishdate2,
			Content content, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		String contents = request.getParameter("content");
		try {
			if (null != publishdate2 && !publishdate2.equals("")) {
				article.setPublishdate(sdf.parse(publishdate2));
			}
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 如果文章id号不为空，则是更新
		if (null != article.getArticleID()) {
			int flagadd = articleService.uparticle(article);
			if (flagadd > 0) {
				flagadd = 0;
				content.setArticleid(article.getContentid());
				flagadd = articleService.upcontent(content);
			}
			if (flagadd > 0) {
				responseMap.put("method", "Create");
				responseMap.put("success", "true");
				responseMap.put("info", "更新成功！");

				response.setContentType("text/html;charset=UTF-8");
				try {
					response.getWriter().write("{success:true}");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}// 如果文章id号为空，则是添加
		else {
			int flagadd = articleService.savearticle(article);
			if (flagadd > 0) {
				flagadd = 0;
				flagadd = articleService.savecontent(content);
			}
			if (flagadd > 0) {
				responseMap.put("method", "Create");
				responseMap.put("success", "true");
				responseMap.put("info", "新增成功！");

				response.setContentType("text/html;charset=UTF-8");
				try {
					response.getWriter().write("{success:true}");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	// 文章列表
	@RequestMapping(value = "/articlelist.do", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject userlist(Params params, String author, String title,
			String source, String articleID, String typeid, String startime,
			String endtime, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// Date startime,Date endtime,
		// StringBuffer toJson=new StringBuffer();//用来放json数据

		// try {
		// if(null!=startime && !"".equals(startime)){
		//
		// Date date = sdf.parse(startime);
		// Date startdate = new SimpleDateFormat("yyyy-MM-dd").parse(startime);
		// params.setStartdate(date);
		// System.out.println(date);
		// }
		// if(null!=endtime && !"".equals(endtime)){
		// Date enddate = new SimpleDateFormat("yyyy-MM-dd").parse(startime);
		// params.setEnddate(enddate);
		// System.out.println(enddate);
		// }
		// } catch (ParseException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		try {
			if (null != startime && !"".equals(startime)) {
				params.setStartdate(sdf.parse(startime));
			}
			if (null != endtime && !"".equals(endtime)) {
				params.setEnddate(sdf.parse(endtime));
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONArray js = new JSONArray();
		// 页码
		int pageno = params.getPage();
		// 每页数量
		int pageSize2 = params.getLimit();
		// int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
		int start = (params.getPage() - 1) * params.getLimit();
		params.setStart(start);
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		// jsonConfig.registerJsonValueProcessor(Date.class, new
		// JsonDateValueProcessor());
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		List articlelist = articleService.getArticleList(params, article);
		int totle = articleService.getartcletotle(params, article);
		obj.put("data", js.fromObject(articlelist, jsonConfig));
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("success", true);

		// /response.setHeader("Cache-Control", "no-cache");
		// response.setContentType("text/json;charset=utf-8");
		// response.getWriter().write(obj.toString());
		// TODO Auto-generated catch block
		// json格式化后输出
		System.out.println(obj.toString());
		return obj;

	}

	// 删除
	@ResponseBody
	@RequestMapping(value = "/delarticle.do", method = RequestMethod.POST)
	public void delarticle(String articleID, String title, String jsonData,
			HttpServletRequest request, HttpServletResponse response) {
		int flagadd = 0;
		int delno = 0;
		Map<String, Object> responseMap = new HashMap<String, Object>();
		String[] temarticleID = articleID.split(",");
		String[] temtitle = title.split(",");
		for (int i = 0; i < temarticleID.length; i++) {
			flagadd = articleService.delarticle(Integer
					.parseInt(temarticleID[i]));
			if (flagadd > 0) {
				flagadd = 0;
				flagadd = articleService.delcontent(temtitle[i]);
				if (flagadd > 0) {
					delno = delno + 1;
				}
			}
		}
		if (delno == temarticleID.length) {
			responseMap.put("method", "del");
			responseMap.put("success", "true");
			responseMap.put("info", "删除成功！");

			response.setContentType("text/html;charset=UTF-8");
			try {
				response.getWriter().write("{success:true}");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 查看
	@ResponseBody
	@RequestMapping(value = "/detailarticle.do", method = RequestMethod.POST)
	public JSONObject detailarticle(int articleID, String title,
			String jsonData, HttpServletRequest request,
			HttpServletResponse response) {
		Object title2;

		title2 = request.getAttribute("title");
		Article article = new Article();
		Content content = new Content();
		JSONObject obj = new JSONObject();
		JSONArray js = new JSONArray();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		Map<String, Object> responseMap = new HashMap<String, Object>();
		article = articleService.detailarticle(articleID);
		// article = articleService.detailarticle(Integer.parseInt(articleID));
		content = articleService.detailcontent(title);
		String contentm = "";
		if (null != content) {
			article.setContent(content.getContent());
			article.setContentid(content.getArticleid());
			contentm = content.getContent();
		}
		Date publishdate2 = article.getPublishdate();
		String publishdate3 = sdf.format(publishdate2);
		System.out.println(publishdate2 + "sdf"
				+ js.fromObject(publishdate2, jsonConfig));
		obj.put("data", js.fromObject(article, jsonConfig));
		obj.put("content", contentm);
		obj.put("publishdate2", publishdate3);
		obj.put("success", true);

		System.out.println(obj.toString());

		return obj;
	}

	// 导出到Excel
	@ResponseBody
	@RequestMapping(value = "/excelarticle.do")
	public void doExportTrafficAccount(HttpServletRequest request,
			HttpServletResponse response)  {
		// 第一步，创建一个webbook，对应一个Excel文件

		HSSFWorkbook wb = new HSSFWorkbook();
		// 构造一个查询条件

		// 创建一个新的Excel
		HSSFWorkbook workBook = new HSSFWorkbook();
		// 创建sheet页
		HSSFSheet sheet = workBook.createSheet();
		// sheet页名称
		workBook.setSheetName(0, "targetStockList");
		// 创建header页
		HSSFHeader header = sheet.getHeader();
		// 设置标题居中
		header.setCenter("标题");
		ObjectExcelView objectExcelView = new ObjectExcelView();

		JSONArray js = new JSONArray();
		// 页码

		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		// jsonConfig.registerJsonValueProcessor(Date.class, new
		// JsonDateValueProcessor());
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		List articlelist = articleService.getArticleList();

		// 通过Response把数据以Excel格式保存

		OutputStream out = null;// 创建一个输出流对象

		try {

			response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ new String(("用户意见信息表" + ".xls").getBytes("GBK"),
							"ISO8859_1") + "\"");
			// .setHeader("Content-disposition", "attachment; filename=" +
			// "我的excel"+".xls");

			// filename是下载的xls的名

			response.setHeader("Pragma", "No-cache");// 设置头

			response.setHeader("Cache-Control", "no-cache");// 设置头

			response.setDateHeader("Expires", 0);// 设置日期头
			out = response.getOutputStream();//
			// new ObjectExcelView().exportExcel(articlelist).write(out);
			objectExcelView.exportExcel(articlelist).write(out);

			out.flush();
			out.close();

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			if (out != null) {

				System.out.println("out 没有 close");

				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

		// return null;
		/*
		 * response.reset();
		 * response.setContentType("application/msexcel;charset=UTF-8"); try {
		 * response.addHeader("Content-Disposition", "attachment;filename=\"" +
		 * new String(("用户意见信息表" + ".xls").getBytes("GBK"), "ISO8859_1") +
		 * "\""); OutputStream outs = response.getOutputStream(); //
		 * workBook.write(outs); outs.flush(); outs.close(); } catch (Exception
		 * e) { e.printStackTrace(); } return;
		 */
		return;
	}

	// 导入到Excel
	@ResponseBody
	@RequestMapping(value = "/importExcel.do")
	public JSONObject importExcel(HttpServletRequest request,
			HttpServletResponse response)  {
		JSONObject obj = new JSONObject();
		// 使用MultipartHttpServletRequest包装文件数据
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 页面控件的文件流

		MultipartFile multipartFile = multipartRequest.getFile("excelfile");
		if (null == multipartFile || "".equals(multipartFile)
				|| multipartFile.isEmpty()) {
			multipartFile = multipartRequest.getFile("excelfile");
		}
		// 获取文件名/
		String filename = multipartFile.getOriginalFilename();
		String logoPathDir = "E:/upload/excels";
		// 得到图片保存目录的真实路径
		String logoRealPathDir = logoPathDir;
		// 根据真实路径创建目录
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists())
			logoSaveFile.mkdirs();
		// StoreLocation
		String fileName = logoRealPathDir + File.separator + filename;
		File file = new File(fileName);
		// 保存上传文件
		try {
			multipartFile.transferTo(file);
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		FileInputStream fis = null;
		List<List> dataList = new ArrayList();
		try {
			fis = new FileInputStream(fileName);
			
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 try {
			dataList = ExcelHelper.getInstanse().excelFileConvertToList(fis);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		for (int i = 1; i < dataList.size(); i++) {
			// article.setArticleID(Integer.parseInt(dataList.get(i).get(0).toString()));
			if(!dataList.get(i).isEmpty() && dataList.get(i).size()>1){
				
				Article article = new Article();
			if (null != dataList.get(i).get(1)) {
				article.setAuthor(dataList.get(i).get(1).toString());

			}
			if (null != dataList.get(i).get(2)) {

				switch (dataList.get(i).get(2).toString()) {
				case "军事":
					article.setChannelid(1);
					break;
				case "财经":
					article.setChannelid(2);
					break;
				case "社会":
					article.setChannelid(3);
					break;
				case "历史":
					article.setChannelid(4);
					break;
				case "文化":
					article.setChannelid(5);
					break;

				}
			}
			if (null != dataList.get(i).get(3)) {
				article.setAddeddate(dataList.get(i).get(3).toString());

			}
			if (null != dataList.get(i).get(4)) {
				article.setSource(dataList.get(i).get(4).toString());

			}
			if (null != dataList.get(i).get(5)) {
				article.setTitle(dataList.get(i).get(5).toString());

			}
			if (null != dataList.get(i).get(6)) {
				try {
					article.setPublishdate(sdf.parse(dataList.get(i).get(6)
							.toString()));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			if (null != dataList.get(i).get(7)) {
				article.setSummary(dataList.get(i).get(7).toString());

			}

			if (null != article) {
				int a = articleService.savearticle(article);
				if(a==1){
					obj.put("success", true);
				}
				else{
					obj.put("failure", true);
				}

			}

			System.out.println(dataList.get(i));

		}
		}
		deleteDir(file);
		obj.put("success", true);
		return obj;
	}
	/**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }
	 /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
	

}
